import { defineStore } from 'pinia'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getInfo } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			nickname: storage.get(constant.nickname),
			avatar: storage.get(constant.avatar),
			phone: storage.get(constant.phone),
			points: storage.get(constant.points) || 0,
			gender: storage.get(constant.gender) || 0,
			birthday: storage.get(constant.birthday),
			userId: storage.get(constant.userId),
			addressName: storage.get(constant.addressName) || '雅安市雨城区',
			addressIds: storage.get(constant.addressIds) || ['51', '5118', '511802'],
			permissions: storage.get(constant.permissions) || []
		}
	},
	getters: {
		
	},
	actions: {
		loginAction(data) {
			return new Promise((resolve, reject) => {
				login(data).then(res => {
					setToken(res.result)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		getInfoAction() {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					let result = res.result || {}
					let user = result.userVO || {}
					this.nickname = user.nickname ? user.nickname : ""
					this.avatar = user.userFile && user.userFile[0] ? user.userFile[0] : null
					this.phone = user.phone ? user.phone : ""
					this.points = user.points ? user.points : 0
					this.gender = user.gender ? user.gender : 0
					this.birthday = user.birthday ? user.birthday : ""
					this.userId = user.userId ? user.userId : ""
					this.permissions = result.permissions ? result.permissions : []
					
					storage.set(constant.nickname, this.nickname)
					storage.set(constant.avatar, this.avatar)
					storage.set(constant.phone, this.phone)
					storage.set(constant.points, this.points)
					storage.set(constant.gender, this.gender)
					storage.set(constant.birthday, this.birthday)
					storage.set(constant.userId, this.userId)
					storage.set(constant.permissions, this.permissions)
					resolve(res.result)
				}).catch(error => {
					reject(error)
				})
			})
		},
		logOutAction() {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					removeToken()
					storage.clean()
					this.nickname = ''
					this.avatar = null
					this.phone = ''
					this.points = ''
					this.gender = ''
					this.birthday = ''
					this.userId = ''
					this.addressName = '雅安市雨城区'
					this.addressIds = ['51', '5118', '511802']
					this.permissions = []
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		addressAction(name, ids) {
			this.addressName = name
			this.addressIds = ids
			
			storage.set(constant.addressName, name)
			storage.set(constant.addressIds, ids)
		}
	}
})